package com.ruoyi.user.controller;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.manage.domain.*;
import com.ruoyi.manage.domain.dto.UserDto;
import com.ruoyi.manage.domain.vo.ActivityUserVo;
import com.ruoyi.manage.domain.vo.DonationVo;
import com.ruoyi.manage.mapper.InvitationCodeMapper;
import com.ruoyi.manage.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * @author ZhangZhongGen
 */
@RestController
@Slf4j
@Api(tags = "用户登录")
@RequestMapping("/userWeixin/user")
public class UserUserController extends BaseController {

    @Autowired
    private IWxMiniService wxMiniService;
    @Autowired
    private IUserService userService;
    @Autowired
    private InvitationCodeMapper invitationCodeMapper;
    @Autowired
    private IDonationService donationService;
    @Autowired
    private IGoodsShelvesService goodsShelvesService;
    @Autowired
    private IActivityService activityService;
    @Autowired
    private IUserDonationService userDonationService;

    @PostMapping("/login/phone")
    @ApiOperation("用户端-手机号登录")
    public AjaxResult phoneLogin(@RequestBody WxLoginRequest request) {
            WxLoginResult result = wxMiniService.wxPhoneLogin(request);
            return AjaxResult.success(result);
    }

    @ApiOperation("用户端-修改用户信息")
    @PutMapping
    public AjaxResult edit(@RequestBody UserDto userDto) {
        User user = new User();
        BeanUtils.copyBeanProp(user, userDto);
        User principal = getUser();
        user.setId(principal.getId());
        return toAjax(userService.updateUser(user));
    }

    @ApiOperation("用户端-赞助商认证")
    @PutMapping("/authentication/sponsor")
    public AjaxResult authenticationSponsor(@RequestBody InvitationCode code) {
        InvitationCode invitationCode = invitationCodeMapper.selectInvitationCodeByInviteCode(code.getCode());
        if (invitationCode == null) {
            return AjaxResult.error("邀请码不存在");
        }else if (invitationCode.getStatus() == 1) {
            return AjaxResult.error("邀请码已使用");
        }
        User principal = getUser();
        User user = User.builder().id(principal.getId()).status(1).inviteCode(code.getCode()).build();
        return AjaxResult.success( userService.updateUser(user));
    }

    @ApiOperation("用户端-学生认证")
    @PutMapping("/authentication/student")
    public AjaxResult authenticationStudent(@RequestBody AuthenticationStudent as) {
        /**
         * TODO 根据学校id和学号验证学生身份-待完成
         */
        System.out.println(as.toString());
        User principal = getUser();
        User user = User.builder()
                .id(principal.getId())
                .status(1)
                .studentId(as.getStudentId())
                .schoolId(as.getSchoolId()).build();
        return AjaxResult.success( userService.updateUser(user));
    }

    @ApiOperation("用户端-查询捐赠信息")
    @GetMapping("/donationList")
    public TableDataInfo myDonateList(@RequestParam Integer pageNum,
                                      @RequestParam Integer pageSize,
                                      @RequestParam(required = false) Integer status,
                                      @RequestParam(required = false) String type){
        User principal = getUser();
        Donation donation = Donation.builder()
                .status(status)
                .build();
        if("pickup".equals(type)){
            donation.setReceiverId(principal.getId());
        }else if ("donate".equals(type)){
             donation.setDonorId(principal.getId());
        }else {
            throw new RuntimeException("参数错误");
        }
        startPage();
        return getDataTable(donationService.selectDonationVoList(donation));
    }
    @ApiOperation("用户端-查询收藏的捐赠信息")
    @GetMapping("/collectDonationVoList")
    public TableDataInfo myCollectDonationVoList(){
        List<DonationVo> list = userDonationService.getCollectDonationVoList(getUser().getId());
        return getDataTable(list);
    }
    /**
     * 取消订单
     */
    @PutMapping("/cancelOrder")
    @ApiOperation("取消订单")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult cancelOrder(@RequestBody CancelOrder cancelOrder) {
        User user = getUser();
        DonationVo dv = donationService.selectDonationVoById(cancelOrder.getId());
        //判断订单是否为待审核或待入库,且用户只能修改自己的订单状态
        if(!user.getId().equals(dv.getDonorId()) || !(dv.getStatus().equals(0)|| dv.getStatus().equals(2))){
            throw new RuntimeException("无权限");
        }
        //如果是待入库订单,需要修改货架信息
        if(dv.getStatus().equals(2)){//取消待入库订单
            GoodsShelves goodsShelves = dv.getGoodsShelves();
            goodsShelves.setShelfStatus(2);
            goodsShelves.setDonationId(null);//清空货架-货物
            goodsShelvesService.updateGoodsShelves(goodsShelves);
        }
        Donation donation = Donation.builder()
                .id(cancelOrder.getId())
                .cancelReason(cancelOrder.getCancelReason())
                .status(1)
                .build();
        return toAjax(donationService.updateDonation(donation));
    }

    /**
     * 用户端-查询活动列表
     * @return
     */
    @ApiOperation("用户端-查询活动列表")
    @GetMapping("/activityUserVoList/{finish}")
    public TableDataInfo getAvtivityList(@PathVariable("finish") Integer finish) {
        startPage();
        List<ActivityUserVo> list = activityService.selectActivityVoList(getUser().getId(),finish);
        return getDataTable(list);
    }

    @ApiOperation("用户端-删除收藏")
    @DeleteMapping("/deleteCollection/{id}")
    public AjaxResult deleteCollection(@PathVariable("id") Long id) {
        UserDonation ud = UserDonation.builder().donationId(id).userId(getUser().getId()).build();
        return AjaxResult.success(userDonationService.delete(ud));
    }

    @ApiOperation("锁定捐赠物")
    @PutMapping("/lockDonation/{id}")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateDonationLock(@PathVariable("id") Long donationId){
        if(donationService.selectDonationById(donationId).getStatus()!=3){
            return error("该捐赠物状态异常");
        }
        User user = getUser();
        if(user.getAvailableTimes()<=0){
            return error("剩余可取次数不足");
        }
        Donation donation = Donation.builder().id(donationId).status(6).receiverId(user.getId()).build();
        user.setAvailableTimes(user.getAvailableTimes()-1);
        userService.updateUser(user);
        return success(donationService.updateDonation(donation));
    }

    /**
     * 获取当前微信用户
     * @return
     */
    public User getUser(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User principal = (User) authentication.getPrincipal();
        return principal;
    }
}
